package com.example.nocodesqlapi.controller;

import com.example.nocodesqlapi.model.SqlConfig;
import com.example.nocodesqlapi.service.SqlConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * SQL配置管理控制器，提供SQL配置的CRUD操作
 */
@RestController
@RequestMapping("/admin/sql-configs")
public class SqlConfigController {
    
    @Autowired
    private SqlConfigService sqlConfigService;
    
    /**
     * 获取所有SQL配置
     */
    @GetMapping
    public List<SqlConfig> getAllSqlConfigs() {
        return sqlConfigService.getAllSqlConfigs();
    }
    
    /**
     * 根据ID获取SQL配置
     */
    @GetMapping("/{id}")
    public ResponseEntity<SqlConfig> getSqlConfigById(@PathVariable Long id) {
        Optional<SqlConfig> sqlConfig = sqlConfigService.getSqlConfigById(id);
        return sqlConfig.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
    
    /**
     * 创建新的SQL配置
     */
    @PostMapping
    public ResponseEntity<SqlConfig> createSqlConfig(@RequestBody SqlConfig sqlConfig) {
        try {
            SqlConfig savedConfig = sqlConfigService.saveSqlConfig(sqlConfig);
            return ResponseEntity.ok(savedConfig);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
    
    /**
     * 更新SQL配置
     */
    @PutMapping("/{id}")
    public ResponseEntity<SqlConfig> updateSqlConfig(
            @PathVariable Long id, 
            @RequestBody SqlConfig sqlConfig) {
        return sqlConfigService.getSqlConfigById(id)
                .map(existingConfig -> {
                    sqlConfig.setId(id);
                    try {
                        SqlConfig updatedConfig = sqlConfigService.saveSqlConfig(sqlConfig);
                        return ResponseEntity.ok(updatedConfig);
                    } catch (Exception e) {
                        // 明确指定泛型类型为 SqlConfig
                        return ResponseEntity.badRequest().body((SqlConfig) null);
                    }
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
    
    /**
     * 删除SQL配置
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSqlConfig(@PathVariable Long id) {
        return sqlConfigService.getSqlConfigById(id)
                .<ResponseEntity<Void>>map(config -> {
                    sqlConfigService.deleteSqlConfig(id);
                    // 显式指定泛型类型为 Void
                    return ResponseEntity.<Void>noContent().build();
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
